<?php
namespace common\bonus;
use common\models\Balance;
use common\models\TradeModel;
use common\utils\CommonFun;
use common\bonus\Validata;
use common\models\Member;
use common\models\StaticInstance;
use common\bonus\StaticRelease;

/*
	团队奖励/级差奖励
	级差奖励   平级奖励 是只拿一代  即往上找到第一个同级差给奖励
*/
class TeamBonus
{

	public static $conf = [];
	
	/*
		*
	*/
	public static function bonusAction($params)
	{
		self::$conf = TradeModel::getTeamBonusConf('TeamBonus');
		if(!self::$conf) return ['state'=>false,'msg'=>'参数配置有误'];
		if(!$params['uper']) return ['state'=>true,'msg'=>'ok'];
		$curConf = self::$conf[0];  //获取一个配置

		$wasRate = 0;
		$bonus = 0;
		$pjFlag = true;
		foreach($params['uper'] as $k=>$member)
		{
		     $state = Member::getOne(['member_id'=>$member],'state');
            if ($state==0){
                continue;
            }
            
			if($k==0) continue;
			$rate = self::getRate($member);
			if($rate<=0) continue;
			$jsRate = $rate - $wasRate;
			if($jsRate<0) continue;
			// var_dump($jsRate);  
			$wasRate = $rate;

			if($jsRate>0)
			{
				//级差
				$bonus = round($params['money']*$jsRate/100,2);
				$params['source_type'] = 3;
				$money = $bonus;
				$pjFlag = true;
			}else
			{
				if(!$pjFlag) continue;
				//平级
				$jsRate = self::getRate($member,2);
				$pjBonus  = round($bonus*$jsRate/100,2);
				$money = $pjBonus;
				$params['source_type'] = 4;
				$pjFlag = false;
			}


			if($curConf['bonus_type'] == 1)
			{
				## 奖励到账本
				self::bonus($member,$money,$curConf,$params);
			}

			if($curConf['bonus_type'] == 2)
			{
				## 加速到静态释放
				$data = array();
				$data['money'] = $money;
				$data['member_id'] = $member['member_id'];
				$data['from_member_id'] = $params['member_id']; 
				$data['source_id'] = $params['source_id']; ;
				$data['static_type'] = 2;				
				StaticRelease::bonusAction($data);
			}
		}
		return ['state'=>true,'msg'=>'ok'];
	}

	protected static function bonus($member,$money,$conf,$params)
	{
		## 帐本分配方式
		$assignType = json_decode($conf['assign_type'],1);
		if(!$assignType) return false;
		foreach($assignType as $btype=>$rate)
		{
			$balance = round($money * $rate / 100 , 2);
			//加入到账本
			$res = Balance::addBalance($member['member_id'],$btype,$balance,$params['source_type'],$params['source_id'],$params['desc']);
			if(!$res['state']){
				$str = '级差奖励 member:'.json_encode($member).' data:'.json_encode($params)."\r\n conf:".json_encode($conf).'msg:'.$res['msg'];
				CommonFun::writeLog($str,'bonus');
			}
		}

		return true;
	}


	## 获取分红比例
	protected static function getRate($member,$type=1)
	{
		$rate = 0;
		foreach(self::$conf as $conf)
		{
			if($conf['grade'] == $member['grade']){
				if($type == 1)
					$rate = $conf['rate'];
				else
					$rate = $conf['pj_rate'];
			} 
		}
		return $rate;
	}




}